package com.xiaotao.user.service.impl;

import com.xiaotao.common.domain.dto.Condition;
import com.xiaotao.common.exceptions.BizIllegalException;
import com.xiaotao.common.utils.SnowflakeIdGenerator;
import com.xiaotao.user.domain.dto.PageDTO;
import com.xiaotao.user.domain.dto.UserDTO;
import com.xiaotao.user.domain.po.User;
import com.xiaotao.user.domain.query.PageQuery;
import com.xiaotao.user.domain.vo.UserListVO;
import com.xiaotao.user.enums.LabelStatus;
import com.xiaotao.user.mapper.UserMapper;
import com.xiaotao.user.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    private final SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1); // 节点 ID 可根据实际情况调整


    // 登录方法login
    @Override
    public User login(UserDTO dto) {
        User user = null;

        // 判断登录方式：优先使用用户名、手机号或邮箱
        if (dto.getPhone() != null && !dto.getPhone().isEmpty()) {
            user = userMapper.selectUserByPhone(dto.getPhone());
        } else if (dto.getEmail() != null && !dto.getEmail().isEmpty()) {
            user = userMapper.selectUserByEmail(dto.getEmail());
        }

        if (user == null) {
            throw new BizIllegalException("用户不存在");
        }

        // 验证密码是否正确
        if (!dto.getPassword().equals(user.getPassword())) {
            throw new BizIllegalException("密码错误");
        }
        return user;
    }

    @Override
    public void register(UserDTO dto) {
        User user = null;
        // 判断登录方式：优先使用用户名、手机号或邮箱
        if (dto.getPhone() != null && !dto.getPhone().isEmpty()) {
            user = userMapper.selectUserByPhone(dto.getPhone());
        } else if (dto.getEmail() != null && !dto.getEmail().isEmpty()) {
            user = userMapper.selectUserByEmail(dto.getEmail());
        }
        // 如果用户已存在，则不允许注册
        if (user != null) {
            throw new BizIllegalException("用户已存在");
        }

        addUser(dto);
    }

    @Override
    public List<UserListVO> getUsers() {
        List<UserListVO> userList = new ArrayList<>();
        userList = userMapper.getUsers();

        return userList;
    }

    /**
     * 根据分页查询对象获取用户列表
     *
     * @param query 分页查询对象，包含页码、页面大小、类别等信息
     * @return 返回一个包含用户列表的分页数据传输对象
     */
    @Override
    public PageDTO<UserListVO> getUsersByPageDTO(PageQuery query) {
        // 获取页码
        Integer pageNo = query.getPageNo();
        // 获取页面大小
        Integer pageSize = query.getPageSize();
        // 获取用户类别
        String category = query.getCategory();

        // todo 条件筛选 根据标签筛选
        // 根据类别字符串获取标签状态对象
        LabelStatus labelStatus = LabelStatus.fromString(category);

        // 封装条件集合
        int currentPage = (pageNo - 1) * pageSize;
        Condition condition = new Condition(currentPage, pageSize);

        // 初始化用户列表
        List<UserListVO> userList = userMapper.getUsersByPage(condition);
        if (userList == null || userList.isEmpty()) {
            throw new BizIllegalException("数据库中没有数据");
        }

        long total = userMapper.getCounts();
        // 返回包含总记录数、总页数和用户列表的分页数据传输对象
        return PageDTO.of(total, total / pageSize, userList);
    }

    @Override
    public void addUser(UserDTO dto) {
        //1.比对dto和po，查找缺失属性 userId
        //1.1 雪花算法生成userId
        long userId = idGenerator.nextId();

        //2.封装dto
        User user = new User();
        user.setUserId(userId);
        user.setUsername(dto.getUsername());
        user.setPassword(dto.getPassword());
        user.setPhone(dto.getPhone());
        user.setEmail(dto.getEmail());
        user.setAvatarUrl(dto.getAvatarUrl());
        user.setGender(dto.getGender());
        user.setDescription("");
        user.setBirthday(dto.getBirthday());
        user.setAddress(dto.getAddress());

        //TODO 捕获或者抛出异常
        //3.调用mapper层接口
        userMapper.addUser(user);
    }


    @Override
    public int selectUserById(Long id) {
        return userMapper.selectUserById(id);
    }

    @Override
    public void deleteUser(Long id) {
        //1.查询数据库，是否存在这条数据
        int count = selectUserById(id);
        if (count == 0) {
            throw new BizIllegalException("查询失败，未知id");
        }
        //2.删除数据
        //TODO 捕获或者抛出异常
        userMapper.deleteUser(id);
    }

}
